'''
Created on Feb 3, 2013

@author: bawey
'''


import cpoo_tools as tools
import cv
import cv2
import numpy as np
import sys
import tesseract
from cpoo_tools import show_wait


image = cv.LoadImage( sys.argv[1] )

image = tools.split_channels( image )
resized = cv.CreateImage( ( ( int )( image.width * ( 640.0 / image.height ) ), 640 ), image.depth, image.nChannels )
cv.Resize( image, resized )
image = resized
image = tools.array2cv( cv2.medianBlur( tools.cv2array( image ), 3 ) ) 
tools.show_wait( image, "cpoo" )

output = tools.text_energy_map( image )

tools.show_wait( output, "cpoo" )

regions = tools.grow_regions( output, 255, 0 )
regions = tools.cluster_regions( image, regions )
regions = tools.kill_the_losers( image, regions )

api = tesseract.TessBaseAPI()
api.Init( ".", "eng", tesseract.OEM_TESSERACT_ONLY )
api.SetVariable( "tessedit_char_whitelist", " 0123456789.:\/\\PM" )
api.SetPageSegMode( tesseract.PSM_SINGLE_LINE )


for region in regions:
    roi_image = tools.extract( image, region )

    result = cv.CreateImage( ( 2 * roi_image.width, 2 * roi_image.height ), roi_image.depth, roi_image.nChannels )
    cv.Resize( roi_image, result )
    tools.show_wait( result, "final result" )
    cv.SaveImage("result.png", result)

    tesseract.SetCvImage( result, api )
    text = api.GetUTF8Text()
    print "scanned text: " + text

